package main

import (
	"database/sql"
	"fmt"

	_ "github.com/lib/pq"
)

var db *sql.DB

type c struct {
	cno   int
	cname string
}

func sqlOpen() {
	var err error
	db, err = sql.Open("postgres", "port=5432 user=postgres password=123456 dbname=fu mode=disable")
	println("数据库连接成功！")

	if err != nil {
		panic(err)
	}

	const (
		host     = "localhost"
		port     = 5432
		user     = "postgres"
		password = "Tss1433223"
		dbname   = "test"
	)

	psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
		"password=%s dbname=%s sslmode=disable",
		host, port, user, password, dbname)
	db, err := sql.Open("postgres", psqlInfo)
	if err != nil {
		panic(err)
	}
	defer db.Close()

	err = db.Ping()
	if err != nil {
		panic(err)
	}

	fmt.Println("Successfully connected!")

	sqlStatement := `
	INSERT INTO c (cno,cname)
	VALUES ($1,$2)
	RETURNING cno,cname`

	var result c
	err = db.QueryRow(sqlStatement, 4, "PE").Scan(&result.cno, &result.cname)
	if err != nil {
		panic(err)
	}
	fmt.Println("Already increased:", result)

}

func main() {
	sqlOpen()
}
